import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    //三数之和
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList();
        int n = nums.length;
        if(n < 3) {
            return list;
        }
        Arrays.sort(nums);
        for(int i = 0; i < n;) {
            int tmp = nums[i];
            twoSum(nums,i,list);
            //去重
            while(i < n && tmp == nums[i]) {
                i++;
            }
        }
        return list;
    }
    private void twoSum(int[] nums, int i, List<List<Integer>> list) {
        int left = i+1;
        int right = nums.length-1;
        while(left < right) {
            if(nums[left] + nums[right] < -nums[i]) {
                left++;
            }else if(nums[left] + nums[right] > -nums[i]) {
                right--;
            }else{
                int tmp = nums[left];
                list.add(Arrays.asList(nums[i],nums[left],nums[right]));
                //去重
                while(left < right && nums[left] == tmp) {
                    left++;
                }
            }
        }
    }
}
